import pexpect
import sys
import time

HOST = "192.168.1.254"
PORT = 23
USERNAME = "admin"
PASSWORD = "Aa123456111"

# 指令列表（故意加了一个不存在的命令）
commands = [
    "system-view",  # 进入 system-view
    "interface GigabitEthernet 0/0/11",
    "shutdown",
    "nonexistent_command"  # 故意写一个错误命令，制造异常
]

def telnet_with_pexpect(host, username, password, commands):
    try:
        print("\n=== 开始Telnet连接 ===")
        child = pexpect.spawn(f"telnet {host}", timeout=10)
        child.logfile = sys.stdout.buffer  # 实时打印交互过程

        child.expect("Username:")  # 等待 Username 提示
        child.sendline(username)

        child.expect("Password:")  # 等待 Password 提示
        child.sendline(password)

        # 登录后执行命令
        for cmd in commands:
            # 正常情况下提示符是 > 或 ]
            index = child.expect([r"[\]>]", r"Username:", r"Password:", pexpect.TIMEOUT, pexpect.EOF], timeout=5)
            if index == 0:
                print(f"\n>>> 发送指令: {cmd}")
                child.sendline(cmd)
                time.sleep(1)
            elif index == 1:
                raise Exception("意外跳回到 Username 提示，可能是认证失败")
            elif index == 2:
                raise Exception("意外跳回到 Password 提示，可能是认证失败")
            elif index == 3:
                raise pexpect.exceptions.TIMEOUT("等待提示符超时")
            elif index == 4:
                raise pexpect.exceptions.EOF("连接意外断开")

        # 退出
        child.expect(r"[\]>]", timeout=5)
        child.sendline("quit")
        child.close()
        print("\n=== Telnet会话正常结束 ===")

    except pexpect.exceptions.EOF as e:
        print("\n❌连接断开:", e)
    except pexpect.exceptions.TIMEOUT as e:
        print("\n⏰连接超时:", e)
    except Exception as e:
        print("\n⚠️发生其他异常:", e)

if __name__ == "__main__":
    telnet_with_pexpect(HOST, USERNAME, PASSWORD, commands)